<?php

namespace app\common\model;

use buwang\base\TimeModel;
use app\manage\model\Member;
use UnexpectedValueException;

class MiniappTerm extends TimeModel
{

    protected $name = "miniapp_term";

    protected $deleteTime = false;


    public function miniapp()
    {
        return $this->belongsTo('\app\common\model\Miniapp', 'miniapp_id', 'id');
    }


    public function getMiniappList()
    {
        return \app\common\model\Miniapp::column('title', 'id');
    }


    /** 应用续费
     * @param $param
     * @param bool $trans
     * @return bool
     * @throws \Exception
     */
    public function renew($param,$trans=false){
        //查询套餐
        $self = self::where('id',$param['id'])->find();
        if(!$self) throw new \Exception('未找到充值套餐');
        if (!isset($param['password'])) throw new \Exception('请填写支付密码');
        $user = Member::where('id',$param['member_id'])->find();
        if(!$user)throw new \Exception('租户不存在');
        //提交支付
        if (!Member::checkPassword($param['password'], $user['safe_password'])) throw new \Exception('支付密码错误');
        $memberMiniapp = MemberMiniapp::where('member_id',$param['member_id'])->where('miniapp_id',$self['miniapp_id'])->find();
        if(!$memberMiniapp)throw new \Exception('未购买该应用');
        if($memberMiniapp['expire_time'] ==0)throw new \Exception('已永久拥有无需购买');
        //应用信息
        $miniapp = Miniapp::where('id',$self['miniapp_id'])->find();
        if(!$miniapp)throw new \Exception('找不到该应用');
        if($trans){
            self::startTrans();
        }
        $time = time();
        //如果应用还未过期，用剩余时间累加
        $memberMiniappOrder = MemberMiniappOrder::where('member_id',$memberMiniapp['member_id'])->where('miniapp_id',$memberMiniapp['miniapp_id'])->where('miniapp_module_id',$self['miniapp_module_id'])->order('create_time desc')->find();
        if($memberMiniappOrder&&$memberMiniappOrder['expire_time']>$time)$time = $memberMiniappOrder['expire_time'];
        try{
            $days = $self['days']==0 ? '到永久':$self['days'].'天';
            //扣费
            \app\common\model\member\Wallet::changeMoney($param['member_id'], 'miniapp', 0 - $self['price'], "应用【{$self['dir']}】续费{$days}");
            //增加应用购买订单记录
            $orderParam = [
                'member_id' => $param['member_id'],        //租户id
                'miniapp_id' => $self['miniapp_id'], //应用id
                'miniapp_module_id' => $self['miniapp_module_id'], //模块id
                'title' => $miniapp['title'],   //应用名
                'update_var' => 0,              //小程序模板ID 0
                'price' => $self['price'],    //模块价格
                'valid_days' => $self['days'], //有效天数
                'expire_time' => $self['days'] > 0 ? $time + $self['days'] * 24 * 60 * 60 : 0, //过期时间
                'miniapp_module_type' => 1, //得到功能类型
            ];
             MemberMiniappOrder::create($orderParam);
            //更新租户应用时长
            $memberMiniapp['expire_time'] =  $self['days'] > 0 ? $time + $self['days'] * 24 * 60 * 60 : 0;
            $memberMiniapp->save();
        }catch (\Exception $e){
            if($trans){
                self::rollback();
            }
            throw new \Exception($e->getMessage());
        }
        return true;
    }


    /**
     * 得到剩余天数
     */
    public static function getDaysRemaining($member_id,$dir=null,$expire_time=0){
        if(!$expire_time && $dir){
            //应用信息
            $miniapp = Miniapp::where('dir',$dir)->find();
            if(!$miniapp)throw new \Exception('找不到该应用');
            $memberMiniapp = MemberMiniapp::where('member_id',$member_id)->where('miniapp_id',$miniapp['id'])->find();
            if(!$memberMiniapp)throw new \Exception('未购买该应用');
            $expire_time = $memberMiniapp['expire_time'];
        }
        if($expire_time == 0)return '永久有效';
        //剩余天数 = (过期时间 - 当前时间)  / 86400
        $sub_time = $expire_time - time();
        if($sub_time<=0)return '已过期';
        return bcdiv($sub_time,86400,0).'天';
    }

    /**
     * 检测并获取应用购买信息.
     *
     * @param int  $uid
     * @param int  $miniappId
     * @param bool $force 强制报错，如果未购买.
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function checkMiniappBought(int $uid, int $miniappId, bool $force = FALSE):array {
        $miniappOrder = MemberMiniappOrder::where(
            ['member_id' => $uid, 'miniapp_id' => $miniappId, 'miniapp_module_type' => 1]
        )
            ->order('id desc')
            ->find();
        // 订单购买记录.
        if (empty($miniappOrder)) {
            if ($force) {
                throw new UnexpectedValueException('应用未购买');
            }

            return [
                'hasBought' => FALSE,
            ];
        }

        // 租户应用.
        $memberMiniApp = MemberMiniapp::where(
            [
                'member_id'  => $uid,
                'miniapp_id' => $miniappOrder->miniapp_id,
            ]
        )
            ->field([
                'id',
                'service_id',
                'appname',
            ])
            ->find();
        if (empty($memberMiniApp)) {
            if ($force) {
                throw new UnexpectedValueException('应用不存在');
            }

            return [
                'hasBought' => FALSE,
            ];
        }

        $remainingDays = -1;
        if ($miniappOrder['expire_time'] == 0) {
            $remainingDays = 0;
        }
        // 剩余天数 = (过期时间 - 当前时间)  / 86400
        $sub_time = $miniappOrder['expire_time'] - time();
        if ($sub_time > 0) {
            $remainingDays = bcdiv($sub_time, 86400);
        }

        return [
            'hasBought'     => TRUE,
            'priceInfo'     => $miniappOrder->price_info,
            'expireTimeMs'  => $miniappOrder['expire_time'],
            'remainingDays' => $remainingDays,
            'app'           => $memberMiniApp->toArray(),
        ];
    }

}